package com.example.musicrunner.client;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class LastFMKey {

	private static final String LastFMMetroTrackChartUrl = 
	"http://ws.audioscrobbler.com/2.0/?method=geo.getmetrotrackchart=united+states&format=json&api_key=b3236de51522255d11172c7da0fd4e8"; 
	private static final int HTTP_STATUS_OK = 200;
	private static byte[] buff = new byte[512];

	
	protected static synchronized String downloadFromServer (String[] params) {
		
		String val = null;
		String metro = params[0]; 
		String url = LastFMMetroTrackChartUrl+"&metro=" + metro; 

		// create request
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(url);

		try {
			// execute request
			HttpResponse response = client.execute(request);
			StatusLine status = response.getStatusLine();
			if (status.getStatusCode() != HTTP_STATUS_OK) {
				// TODO Auto-generated catch block
				throw new Exception("Invalid response from last.fm" + status.toString());
			}

			// process the content. 
			HttpEntity entity = response.getEntity();
			InputStream ist = entity.getContent();
			ByteArrayOutputStream content = new ByteArrayOutputStream();

			int readCount = 0;
			while ((readCount = ist.read(buff)) != -1) {
				content.write(buff, 0, readCount);
			}
			val = new String (content.toByteArray());

	    } catch (Exception e) {
	    	// TODO Auto-generated catch block
		    	e.getMessage();
		  }

		return val;
	}
}
